package cn.yunhe.crm.realm;


import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import cn.yunhe.crm.entity.Emp;
import cn.yunhe.crm.service.EmpService;

public class MyRealm extends AuthorizingRealm{
	
	@Autowired
	@Qualifier("EmpService")
	private EmpService eService;
	
	public void seteService(EmpService eService) {
		this.eService = eService;
	}

	/**
	 * 为当前用户授予权限
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username=(String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
		authorizationInfo.setRoles(eService.getRoles(username));
		authorizationInfo.setStringPermissions(eService.getPermissions(username));
		return authorizationInfo;
	}
	
	
	/** 
	 * 验证当前登录用户
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username=(String) token.getPrincipal();
		Emp emp=eService.getByUserName(username);
		try {
			if(emp!=null){
				AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(emp.getUsername(),emp.getPassword(),emp.getEmpname());
				return authcInfo;
			}else{
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();  
		} 
		return null;
	}

}
